import { defineStore } from "pinia";
import { ref, unref } from "vue";
import store from "./store";
import { AppDto } from "./app.store";

const key = "mod";
const useModStore = defineStore(key, () => {
  const modList = ref<AppDto[]>([]);

  const initMod = async () => {
    const modStore = await (await store).get(key);
    console.log(modStore);
    if (modStore) {
      modList.value = modStore as unknown as AppDto[];
    }
    return unref(modList);
  };
  const genMod = (name: string = "", code: string = "") => {
    const modLen = modList.value.length;
    const last = modLen === 0 ? -1 : modLen - 1;
    const id = last === -1 ? 0 : Number(modList.value[last].id) + 1;
    return new AppDto(id, name, code, "");
  };
  const findOne = (id: number) => {
    const one = modList.value.find((item) => item.id === id);
    return one || null;
  };
  const addMod = async (mod: AppDto) => {
    modList.value.push(mod);
    await (await store).set(key, unref(modList));
  };
  const delMod = async (id: number) => {
    modList.value = modList.value.filter((item) => item.id !== id);
    await (await store).set(key, unref(modList));
  };
  return {
    modList,
    initMod,
    genMod,
    findOne,
    addMod,
    delMod,
  };
});

export default useModStore;
